package com.zealfi.wk.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by kuan at 2018-04-28 下午 12:29
 */
public class AccessFilter extends ZuulFilter {
    public static final Logger logger = LoggerFactory.getLogger(AccessFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());

        String token = request.getParameter("accessToken");
        if (StringUtils.isEmpty(token)) {
            logger.warn("token is empty");

            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);

            return null;
        }

        logger.info("access token:{} ok", token);
        return null;
    }
}
